#-*-coding:utf-8-*-
import os
import sys
import nuke
import nukescripts
if sys.version>'3':
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *
else:
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *

"""
ParmControlWindow: 参数控制窗口
    实现功能： 对选择的多个Read节点，可以进行常用属性的批量更改操作
"""

class ParmControlWindow(QDialog):

    def __init__(self,parent=None):
        super(ParmControlWindow, self).__init__(parent)
        #全局变量
        self.format_list=[]  #所有的格式列表
        self.module_data={}  #模板数据,用来批量设置

        self.setWindowTitle('参数控制')
        self.main_layout=QVBoxLayout()
        # self.main_layout.setAlignment(Qt.AlignLeft)
        self.format_layout=QHBoxLayout()
        self.format_layout.setAlignment(Qt.AlignLeft)
        self.format_label=QLabel('format:')
        self.format_comb=QComboBox()
        self.init_format_comb()
        self.custom_format_label=QLabel('custom format:')
        self.custom_x_edit=QLineEdit()
        self.custom_y_edit=QLineEdit()
        self.format_layout.addWidget(self.format_label)
        self.format_layout.addWidget(self.format_comb)
        self.format_layout.addWidget(self.custom_format_label)
        self.format_layout.addWidget(self.custom_x_edit)
        self.format_layout.addWidget(self.custom_y_edit)
        self.frame_range_layout=QHBoxLayout()
        self.frame_range_label=QLabel('frame range:')
        self.frame_first_edit=QLineEdit()
        self.frame_before_comb=QComboBox()
        self.frame_last_edit=QLineEdit()
        self.frame_after_comb=QComboBox()
        self.init_frame_first_end_type()
        self.frame_range_layout.addWidget(self.frame_range_label)
        self.frame_range_layout.addWidget(self.frame_first_edit)
        self.frame_range_layout.addWidget(self.frame_before_comb)
        self.frame_range_layout.addWidget(self.frame_last_edit)
        self.frame_range_layout.addWidget(self.frame_after_comb)
        self.frame_expression_layout=QHBoxLayout()
        self.frame_expression_label=QLabel('frame:')
        self.frame_expression_comb=QComboBox()
        self.init_frame_expression()
        self.frame_expression_edit=QLineEdit()
        self.frame_expression_layout.addWidget(self.frame_expression_label)
        self.frame_expression_layout.addWidget(self.frame_expression_comb)
        self.frame_expression_layout.addWidget(self.frame_expression_edit)
        self.original_layout=QHBoxLayout()
        self.original_label=QLabel('original range:')
        self.original_start_edit=QLineEdit()
        self.original_end_edit=QLineEdit()
        self.original_layout.addWidget(self.original_label)
        self.original_layout.addWidget(self.original_start_edit)
        self.original_layout.addWidget(self.original_end_edit)
        self.colorspace_layout=QHBoxLayout()
        self.colorspace_layout.setAlignment(Qt.AlignLeft)
        self.colorspace_label=QLabel('colorspace:')
        self.colorspace_comb=QComboBox()
        self.init_colorspace()
        self.premultiplied_checkbox=QCheckBox('premultiplied')
        self.raw_data_checkbox=QCheckBox('raw data')
        self.auto_alpha_checkbox=QCheckBox('auto alpha')
        self.colorspace_layout.addWidget(self.colorspace_label)
        self.colorspace_layout.addWidget(self.colorspace_comb)
        self.colorspace_layout.addWidget(self.premultiplied_checkbox)
        self.colorspace_layout.addWidget(self.raw_data_checkbox)
        self.colorspace_layout.addWidget(self.auto_alpha_checkbox)
        self.btn_btn_layout=QHBoxLayout()
        btn_style = ''' QPushButton{color:black}
                                    QPushButton:hover{color:red}
                                    QPushButton{background-color:#FFDEAD}
                                    QPushButton{border:2px}
                                    QPushButton{border-radius:3px}
                                    QPushButton{padding:1px 1px} '''
        self.patch_btn=QPushButton('读取')
        self.patch_btn.clicked.connect(self._patch)
        self.patch_btn.setStyleSheet(btn_style)
        self.OK_btn=QPushButton('设置')
        self.OK_btn.clicked.connect(self._set_all)
        self.OK_btn.setStyleSheet(btn_style)
        self.NO_btn=QPushButton('取消')
        self.NO_btn.setStyleSheet(btn_style)
        self.btn_btn_layout.addWidget(self.patch_btn)
        self.btn_btn_layout.addWidget(self.OK_btn)
        self.btn_btn_layout.addWidget(self.NO_btn)

        self.main_layout.addLayout(self.format_layout)
        self.main_layout.addLayout(self.frame_range_layout)
        self.main_layout.addLayout(self.frame_expression_layout)
        self.main_layout.addLayout(self.original_layout)
        self.main_layout.addLayout(self.colorspace_layout)
        self.main_layout.addLayout(self.btn_btn_layout)
        self.setLayout(self.main_layout)

    def getFormat(self,format_type):
        s = format_type.split(' ')
        two = s[-1].split('x')
        return int(two[0]), int(two[1])

    def init_format_comb(self):
        format_list=['PC_Video          640x488','NTSC              720x486','PAL               720x576','NTSC_16:9         720x486','PAL_16:9          720x576',
                     'HD_720           1280x720','HD_1080         1920x1080','UHD_4K          3840x2160','1K_Super_35      1024x778','1K_Cinemascope    914x778',
                     '2K_Super_35     2048x1080','2K_Cinemascope  1828x1556','2K_DCP          2048x1080','4K_Super_35     4096x3112','4K_Cinemascope  3656x3112',
                     '4K_DCP          4096x2160','square_256        256x256','square_512        512x512','square_1K       1024x1024','square_2K       2048x2048']
        self.format_list=format_list
        self.format_comb.addItems(format_list)

    def init_frame_first_end_type(self):
        comb_list=['hold','loop','bounce','black']
        self.frame_before_comb.addItems(comb_list)
        self.frame_after_comb.addItems(comb_list)

    def init_frame_expression(self):
        comb_list=['expression','start at','offset']
        self.frame_expression_comb.addItems(comb_list)

    def init_colorspace(self):
        comb_list=['default(sRGB)','linear','sRGB','rec709','Cineon','Gamma1.8','Gamma2.2','Gamma2.4','Panalog','REDLog',
                   'ViperLog','AlexaV3LogC','PLogLin','SLog','SLog1','SLog2','SLog3','CLog','Protune','REDSpace']
        self.colorspace_comb.addItems(comb_list)

    def _patch(self):
        data={}
        n=nuke.selectedNode()
        if n.Class()=='Read':
            print('Node:',n)
            current_format=n['format'].value()
            frame_range_first = n['first'].value()
            frame_range_before = n['before'].value()
            frame_range_last = n['last'].value()
            frame_range_after = n['after'].value()
            frame_mode = n['frame_mode'].value()
            frame = n['frame'].value()
            origfirst = n['origfirst'].value()
            origlast = n['origlast'].value()
            colorspace = n['colorspace'].value()
            premultiplied = n['premultiplied'].value()
            raw = n['raw'].value()
            auto_alpha = n['auto_alpha'].value()

            data['format']=current_format
            data['first']=frame_range_first
            data['before']=frame_range_before
            data['last']=frame_range_last
            data['after']=frame_range_after
            data['frame_mode']=frame_mode
            data['frame']=frame
            data['origfirst']=origfirst
            data['origlast']=origlast
            data['colorspace']=colorspace
            data['premultiplied']=premultiplied
            data['raw']=raw
            data['auto_alpha']=auto_alpha
            print('data:',data)
            self.set_pre(data)
        else:
            QMessageBox.information(self,'提示','请选择Read节点')



    def check_format(self,text):
        isin=False
        index=-1
        for i in self.format_list:
            if i.count(text)>0:
                isin= True
                index=self.format_list.index(i)
                break
        return isin,index

    def set_pre(self,data):
        back_data={}
        if data:
            format=data['format']
            width=format.width()
            height=format.height()
            rev=str(width)+'x'+str(height)
            print(rev)
            isin,index=self.check_format(rev)
            if isin:
                self.format_comb.setCurrentIndex(index)
            else:
                self.format_comb.addItem(rev)
                self.format_comb.setCurrentText(rev)
                self.format_list.append(rev)
            self.frame_first_edit.setText(str(data['first']))
            self.frame_before_comb.setCurrentText(data['before'])
            self.frame_last_edit.setText(str(data['last']))
            self.frame_after_comb.setCurrentText(data['after'])
            self.frame_expression_comb.setCurrentText(data['frame_mode'])
            self.frame_expression_edit.setText(data['frame'])
            self.original_start_edit.setText(str(data['origfirst']))
            self.original_end_edit.setText(str(data['origlast']))
            self.colorspace_comb.setCurrentText(data['colorspace'])
            self.premultiplied_checkbox.setChecked(data['premultiplied'])
            self.raw_data_checkbox.setChecked(data['raw'])
            self.auto_alpha_checkbox.setChecked(data['auto_alpha'])
            back_data=data

        return back_data

    def get_module_data(self):
        """
        获取模板数据
        :return:
        """
        data={}
        format=self.format_comb.currentText()
        width,height=self.getFormat(format)
        custom_width=self.custom_x_edit.text()
        custom_height=self.custom_y_edit.text()
        frame_first=self.frame_first_edit.text()
        frame_last=self.frame_last_edit.text()
        frame_before=self.frame_before_comb.currentText()
        frame_after=self.frame_after_comb.currentText()
        frame_model=self.frame_expression_comb.currentText()
        frame_express=self.frame_expression_edit.text()
        origfirst=self.original_start_edit.text()
        origlast=self.original_end_edit.text()
        colorspace=self.colorspace_comb.currentText()
        premultiplied=self.premultiplied_checkbox.isChecked()
        raw=self.raw_data_checkbox.isChecked()
        auto_alpha=self.auto_alpha_checkbox.isChecked()

        data['format']=(width,height) if not custom_width and not custom_height else (int(custom_width),int(custom_height))
        data['first']=frame_first
        data['last']=frame_last
        data['before']=frame_before
        data['after']=frame_after
        data['frame_mode']=frame_model
        data['frame']=frame_express
        data['origfirst']=origfirst
        data['origlast']=origlast
        data['colorspace']=colorspace
        data['premultiplied']=premultiplied
        data['raw']=raw
        data['auto_alpha']=auto_alpha

        print('new_data:',data)
        self.module_data=data
        return data

    def _set_all(self):
        """
        设置所有节点信息
        :return:
        """
        try:
            self.get_module_data()
            if self.module_data:
                for i in nuke.selectedNodes():
                    if i.Class()=='Read':
                        format=i['format'].value()
                        format.setWidth(self.module_data['format'][0])
                        format.setHeight(self.module_data['format'][1])
                        i['format'].setValue(format)
                        i['first'].setValue(int(self.module_data['first']))
                        print('_set_all 01')
                        i['before'].setValue(self.module_data['before'].encode('utf-8'))
                        print('_set_all 02')
                        i['last'].setValue(int(self.module_data['last']))
                        i['after'].setValue(self.module_data['after'].encode('ascii'))
                        i['frame_mode'].setValue(self.module_data['frame_mode'].encode('ascii'))
                        i['frame'].setValue(self.module_data['frame'])
                        i['origfirst'].setValue(int(self.module_data['origfirst']))
                        i['origlast'].setValue(int(self.module_data['origlast']))
                        i['colorspace'].setValue(self.module_data['colorspace'].encode('ascii'))
                        print('_set_all 03')
                        i['premultiplied'].setValue(self.module_data['premultiplied'])
                        i['raw'].setValue(self.module_data['raw'])
                        i['auto_alpha'].setValue(self.module_data['auto_alpha'])
                        print('_set_all 04')
        except Exception as _set_all_ERR:
            print(str(_set_all_ERR))



if __name__ == '__main__':
    app=QApplication(sys.argv)
    p=ParmControlWindow()
    p.show()
    sys.exit(app.exec_())